package rent.hj.videoplayer.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.hg.library.config.FParser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangjianqiang on 2017/12/19 15:13.
 * Package name rent.hj.videoplayer.service
 */

public class UpdateService extends Service {
    private List<String> deleteFiles;
    private List<String> copyFile;
    private MyThread myThread;
    private long time = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getApplicationContext(), "拷贝中", Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    Toast.makeText(getApplicationContext(), "拷贝完毕", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        deleteFiles = new ArrayList<>();
        copyFile = new ArrayList<>();
        myThread = new MyThread();
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String path = intent.getStringExtra("usbpath") + "/" + FParser.VIDEO_FOLDER_NAME;
        update(path);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void update(String path) {
        deleteFiles.clear();
        copyFile.clear();
        try {
            File file = new File(path);
            if (file.exists()) {
                File deleteFile = new File(path + "/deleteVideos.txt");
                if (deleteFile.exists()) {
                    FileInputStream inputStream = new FileInputStream(deleteFile);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        deleteFiles.add(line);
                    }
                }
                File[] files = file.listFiles();
                if (files != null && files.length > 0) {
                    for (int i = 0; i < files.length; i++) {
                        File file1 = files[i];
                        String name = file1.getName();
                        if (name.endsWith(".MP4") || name.endsWith(".mp4") || name.endsWith(".png") || name.endsWith(".PNG")) {
                            copyFile.add(file1.getPath());
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        if (deleteFiles.size() > 0 || copyFile.size() > 0) {
            if (myThread == null) {
                myThread = new MyThread();
            } else {
                try {
                    myThread.interrupt();
                    myThread = new MyThread();
                } catch (Exception e) {

                }
            }
            myThread.start();
        }
    }

    private class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            for (int i = 0; i < deleteFiles.size(); i++) {
                try {
                    deleteFile(deleteFiles.get(i));
                } catch (Exception e) {

                }
            }
            for (int i = 0; i < copyFile.size(); i++) {
                try {
                    File file = new File(copyFile.get(i));
                    String name = file.getName();
                    File parent = new File(Environment.getExternalStorageDirectory().getPath() + "/" + FParser.VIDEO_FOLDER_NAME);
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    String toFile = Environment.getExternalStorageDirectory().getPath() + "/" + FParser.VIDEO_FOLDER_NAME + "/" + name;
                    File ftoFile = new File(toFile);
                    boolean needCopy = true;
                    if (ftoFile.exists()) {
                        long tolength = ftoFile.length();
                        File fromFile = new File(copyFile.get(i));
                        long fromlength = fromFile.length();
                        if (tolength != fromlength) {
                            ftoFile.delete();
                        }else{
                            needCopy = false;
                        }
                    }
                    if(needCopy){
                        CopySdcardFile(copyFile.get(i), toFile);
                    }
                } catch (Exception e) {
                    Log.e("fuck you", e.toString());
                }
            }
            mHandler.removeMessages(0);
            mHandler.sendEmptyMessage(1);
        }
    }

    public boolean CopySdcardFile(String fromFile, String toFile) {
        InputStream fosfrom = null;
        OutputStream fosto = null;
        try {
            fosfrom = new FileInputStream(fromFile);
            File file = new File(toFile);
            if (!file.createNewFile()) {
                return false;
            }
            fosto = new FileOutputStream(file);
            byte bt[] = new byte[1024 * 1024];
            int c;
            while ((c = fosfrom.read(bt)) != -1) {
                fosto.write(bt, 0, c);
                if (System.currentTimeMillis() - time > 3000) {
                    time = System.currentTimeMillis();
                    mHandler.sendEmptyMessage(0);
                }
            }
            fosfrom.close();
            fosto.close();
            return true;

        } catch (Exception ex) {
            try {
                fosfrom.close();
                fosto.close();
            } catch (Exception e) {

            }
            return false;
        }
    }
}
